package service

import (
	"context"
	"encoding/json"
	"goqk/blockchain"
	"goqk/core/events"
	"goqk/core/p2p"
)

// ConsensusService type.
type ConsensusService struct {
}

// var clientConn net.Conn
// var connected = false

// HandleCommitTransaction function
func (ls *ConsensusService) HandleCommitTransaction(ctx context.Context, args *p2p.Args, reply *p2p.Reply) error {
	// reqMeta := ctx.Value(share.ReqMetaDataKey).(map[string]string)
	// resMeta := ctx.Value(share.ResMetaDataKey).(map[string]string)

	// fmt.Printf("received meta: %+v\n", reqMeta)

	// resMeta["echo"] = "from server"
	// clientConn = ctx.Value(server.RemoteConnContextKey).(net.Conn)
	// reply.C = args.A * args.B
	// connected = true

	var tran *blockchain.Transaction
	err := json.Unmarshal([]byte(args.Data), &tran)
	if err != nil {
		// log.Fatal()
		reply.Data = "error"
		return nil
	}

	// 确认签名
	// reply.Data = node.Signature()
	reply.Data = "ok"
	go events.Publish(events.Event{Sender: "", Flag: "", Context: []byte("")})
	return nil
}

// HandleCommitBlock function
func (ls *ConsensusService) HandleCommitBlock(ctx context.Context, args *p2p.Args, reply *p2p.Reply) error {
	var block *blockchain.Block
	err := json.Unmarshal([]byte(args.Data), &block)
	if err != nil {
		// log.Fatal()
		reply.Data = "error"
		return nil
	}

	// 确认签名
	// reply.Data = node.Signature()
	reply.Data = "ok"
	go events.Publish(events.Event{Sender: "", Flag: "", Context: []byte("")})
	return nil

}

// AsynWorldState function
func (ls *ConsensusService) AsynWorldState(ctx context.Context, args *p2p.Args, reply *p2p.Reply) error {
	go events.Publish(events.Event{Sender: "", Flag: "", Context: []byte("")})
	return nil
}

// AsynBlocks function
func (ls *ConsensusService) AsynBlocks(ctx context.Context, args *p2p.Args, reply *p2p.Reply) error {
	go events.Publish(events.Event{Sender: "", Flag: "", Context: []byte("")})
	return nil
}

// Add function
func (ls *ConsensusService) Add(ctx context.Context, args *p2p.Args, reply *p2p.Reply) error {
	go events.Publish(events.Event{Sender: "", Flag: "", Context: []byte("")})
	// reply.C = args.A + args.B
	// fmt.Printf("call: %d + %d = %d\n", args.A, args.B, reply.C)
	return nil
}
